/*
 * @Date: 2023-08-01 13:41:38
 * @LastEditors: bb_c_e_f 961166897@qq.com
 * @LastEditTime: 2023-08-28 20:47:33
 * @FilePath: \part-cloud-appd:\wgwl\veteran_cadre_app\src\api\index.ts
 */
import http, { BASE_URL } from './request'
import { useAppStore } from '@/stores/app-store'

export type HttpData = Record<string | number | symbol, unknown>

export const get = <T>(url: string, config?: Api.Config): Promise<Api.Response<T>> => http.get<T, Api.Response<T>>(url, { custom: config })

export function post<T>(url: string, data?: HttpData | ArrayBuffer, config?: Api.Config): Promise<Api.Response<T>> {
  return http.post<T, Api.Response<T>>(url, data, { custom: config })
}

export function put<T>(url: string, data?: HttpData | ArrayBuffer, config?: Api.Config): Promise<Api.Response<T>> {
  return http.put<T, Api.Response<T>>(url, data, { custom: config })
}

export function del<T>(url: string, config?: Api.Config): Promise<Api.Response<T>> {
  return http.delete<T, Api.Response<T>>(url, { custom: config })
}

export function upload(tempPath: string, uuid: number, progressCallBack: Function): Promise<Api.BasicInstance> {
  const appStore = useAppStore()
  uni.showLoading({
    title: '加载中...',
    mask: true,
  })
  return new Promise((resolve) => {
    const uploadTask = uni.uploadFile({
      url: `${BASE_URL}/app/appConfig/upload`,
      filePath: tempPath,
      header: {
        Authorization: `Bearer ${appStore.state.token}`,
      },
      name: 'file',
      success: (res) => {
        const { data, statusCode } = res
        if (statusCode === 200) {
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-expect-error
          uni.hideLoading({ success: () => { } })
          const resData = JSON.parse(data)
          return resolve(resData.data.url)
        }
      },
      fail: () => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        uni.hideLoading({ success: () => { } })
        uni.showToast({ title: '图片上传失败，稍后重试！', icon: 'none' })
      },
    })
    // 通过uploadTask 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      progressCallBack(res)
    })
  })
}
